const log4js = require('koa-log4');
const logger = log4js.getLogger('user');

module.exports = (app) => {
  app.on("error", (err, ctx) => {
    logger.error(err, '===>on error');
    let {
      status = 404,
        msg = 'not Found'
    } = err;
    switch (status) {
      case 500:
        msg = '服务器异常'
        break;
    }
    ctx.body = {
      status,
      msg
    };
  });
  app.on('success', (result, ctx) => {
    let {
      status = 200, data = null, msg = 'success'
    } = result;
    ctx.body = {
      status: status,
      data,
      msg: msg
    }
  });
  app.use(async (ctx, next) => {
    await next().catch(err => {
      logger.error(err, '===>on error')
      let status = err.statusCode || err.status || ctx.status || 500;
      ctx.app.emit('error', {
        status: status
      }, ctx);
    })

  })
}
